package com.liang.eight_DeadQueue;

import com.rabbitmq.client.*;
import utils.RabbitmqUtil;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeoutException;

/**
 * Created with IntelliJ IDEA.
 * User: XIAOLIANG
 * Date: 2021/6/18
 * Time: 21:11
 * Description: 死信队列 正常的消费者
 *
 * 需要包含两个交换机 两个队列
 *
 */
public class Consumer01 {

    //正常的交换机
    public static final String NORMAL_EXCHANGE = "normal_exchange";
    //死信交换机
    public static final String DEAD_EXCHANGE = "dead_exchange";
    //正常的队列
    public static final String NORMAL_QUEUE = "normal_queue";
    //死信队列
    public static final String DEAD_QUEUE = "dead_queue";


    public static void main(String[] args) throws IOException, TimeoutException {

        Channel channel = RabbitmqUtil.getChannel();

        //声明 普通 和死信交换机

        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);
        channel.exchangeDeclare(DEAD_EXCHANGE,BuiltinExchangeType.DIRECT);


        //声明普通队列
        HashMap<String, Object> arguments = new HashMap<>();
//        arguments.put("x-message-ttl",);//设置过期时间  可以由生产者设置 过期时间
        arguments.put("x-dead-letter-exchange",DEAD_EXCHANGE); //设置 死信交换机
        arguments.put("x-dead-letter-routing-key","lisi");//设置 死信 的routing key
        channel.queueDeclare(NORMAL_QUEUE,false,false,false,arguments);

        //和死信队列
        channel.queueDeclare(DEAD_QUEUE,false,false,false,null);


        /**
         * 将交换机 和对应的队列进行捆绑
         */
        //普通 交换机 绑定普通队列
        channel.queueBind(NORMAL_QUEUE,NORMAL_EXCHANGE,"zhangsan");

        //死信交换机 和死信队列进行绑定
        channel.queueBind(DEAD_QUEUE,DEAD_EXCHANGE,"lisi");



        //消息的 接受 消费
        channel.basicConsume(NORMAL_QUEUE,true,new DeliverCallback(){

            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                System.out.println(new String(message.getBody(),"UTF-8"));
            }
        },new CancelCallback(){

            @Override
            public void handle(String consumerTag) throws IOException {

            }
        });


    }





}